package com.jzsk.variable.center.service.user;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jzsk.variable.center.common.utils.DateUtils;
import com.jzsk.variable.center.dao.zhengxin.entity.SysUser;
import com.jzsk.variable.center.dao.zhengxin.mapper.SysUserMapper;
import com.jzsk.variable.center.domain.dto.user.LoadUserReqDTO;
import com.jzsk.variable.center.domain.dto.user.LoadUserRespDTO;
import com.jzsk.variable.center.domain.dto.user.UserInfo;
import com.jzsk.variable.center.domain.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    SysUserMapper sysUserMapper;

    @Override
    public ResponseVO<LoadUserRespDTO> loadUsers(LoadUserReqDTO loadUserReqDTO) {
        Page<SysUser> page = new Page<>(loadUserReqDTO.getPage(), loadUserReqDTO.getPageSize());
        Page<SysUser> sysUserPage = sysUserMapper.selectPage(page, Wrappers.lambdaQuery(new SysUser())
                .like(StrUtil.isNotEmpty(loadUserReqDTO.getUserName().trim()), SysUser::getName, loadUserReqDTO.getUserName())
                .orderByDesc(SysUser::getUpdateTime));

        List<UserInfo> retUserList = convertUserInfo(sysUserPage.getRecords());

        LoadUserRespDTO loadUserRespDTO = LoadUserRespDTO.builder()
                .userList(retUserList)
                .total(sysUserPage.getTotal())
                .build();
        return ResponseVO.success(loadUserRespDTO);
    }

    private List<UserInfo> convertUserInfo(List<SysUser> sysUserList) {
        return sysUserList.stream().map(sysUser -> UserInfo.builder()
                .name(sysUser.getName())
                .loginName(sysUser.getLoginName())
                .createTime(DateUtils.formatDateTime(sysUser.getCreateTime()))
                .updateTime(DateUtils.formatDateTime(sysUser.getUpdateTime()))
                .updateUser(sysUser.getUpdateUser())
                .build()).collect(Collectors.toList());
    }

}
